package edu.hnu.userserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hnu.commonutils.Result;
import edu.hnu.commonutils.UserDb.TradersResponse;
import edu.hnu.userserver.auth.JwtOperator;
import edu.hnu.userserver.entity.Traders;
import edu.hnu.userserver.model.LoginResponse;
import edu.hnu.userserver.service.TradersService;
import edu.hnu.userserver.mapper.TradersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class TradersServiceImpl extends ServiceImpl<TradersMapper, Traders>
    implements TradersService{
      @Autowired
     TradersMapper tradersMapper;
     @Autowired
      JwtOperator jwtOperator;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public TradersServiceImpl() {
    }

    @Override
   public Result TraderLogin(String usernameOrEmail, String password){
        System.out.println(usernameOrEmail+password);
        Traders traders = tradersMapper.selectOne(
               new LambdaQueryWrapper<Traders>()
                       .eq(Traders::getPassword,password)
                       .and(
                           i->i.eq(Traders::getUsername,usernameOrEmail)
                                   .or()
                                   .eq(Traders::getEmail,usernameOrEmail)
                       )
       );
        System.out.println(traders);
       if(traders==null){
           return Result.error().data(traders);
       }
       else {
           Map<String,Object> traderInfoMap = buildTokenTraderInfo(traders);
           String token = jwtOperator.generateToken(traderInfoMap);
           String key = "1"+traders.getTraderId().toString();
           stringRedisTemplate.opsForValue().set(key,token);
           LoginResponse loginResponse = new LoginResponse(token);
           return Result.ok(loginResponse,"登录成功");
       }
   }
@Override
   public  TradersResponse getTraderDetail(Integer id){
       Traders traders = tradersMapper.selectById(id);
       TradersResponse tradersResponse = new TradersResponse();
       tradersResponse.setUsername(traders.getUsername());
       tradersResponse.setEmail(traders.getEmail());
       return tradersResponse;
   }

    public Map<String, Object> buildTokenTraderInfo(Traders traders) {
        Map<String, Object> map = new HashMap<>();
        // 管理员的id和user_type
        map.put("id", traders.getTraderId());
        map.put("user_type", 1);
        return map;
    }

}




